package database

import (
	"fmt"
	"strings"

	"changeme/internal/models"
)

// FormatColumnType 格式化列类型，统一不同数据库系统的列类型表示
func FormatColumnType(columnInfo *models.ColumnInfo, dbType models.DatabaseType) {
	// 对于DaMeng数据库，类型处理已经在buildColumnInfo中完成，这里保留原始值
	if dbType == models.DaMeng {
		// 对于达梦数据库，我们已经在DaMengDriver.buildColumnInfo中正确处理了类型
		// 不对类型做任何转换，保留其原始值
		return
	}

	// 对于其他数据库，统一类型名称为小写
	columnInfo.Type = strings.ToLower(columnInfo.Type)

	// 构建完整类型表示
	switch dbType {
	case models.MySQL:
		formatMySQLColumnType(columnInfo)
	case models.PostgreSQL:
		formatPostgreSQLColumnType(columnInfo)
	case models.SQLite:
		formatSQLiteColumnType(columnInfo)
	case models.SQLServer:
		formatSQLServerColumnType(columnInfo)
	}

	// 处理别名属性，确保前端兼容性
	columnInfo.NotNull = !columnInfo.IsNullable
	columnInfo.PrimaryKey = columnInfo.IsPrimaryKey
	columnInfo.AutoIncrement = columnInfo.IsAutoIncrement
}

// formatMySQLColumnType 格式化MySQL列类型
func formatMySQLColumnType(columnInfo *models.ColumnInfo) {
	// 如果已经有完整类型信息，直接使用
	if columnInfo.FullType != "" {
		return
	}

	// 按MySQL类型格式构建完整类型
	switch strings.ToLower(columnInfo.Type) {
	case "varchar", "char", "binary", "varbinary":
		if columnInfo.Length > 0 {
			columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Length)
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	case "decimal", "numeric", "float", "double":
		if columnInfo.Precision > 0 {
			if columnInfo.Scale > 0 {
				columnInfo.FullType = fmt.Sprintf("%s(%d,%d)", columnInfo.Type, columnInfo.Precision, columnInfo.Scale)
			} else {
				columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Precision)
			}
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	case "enum", "set":
		if len(columnInfo.Values) > 0 {
			values := make([]string, len(columnInfo.Values))
			for i, v := range columnInfo.Values {
				values[i] = "'" + v + "'"
			}
			columnInfo.FullType = fmt.Sprintf("%s(%s)", columnInfo.Type, strings.Join(values, ","))
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	default:
		columnInfo.FullType = columnInfo.Type
	}
}

// formatPostgreSQLColumnType 格式化PostgreSQL列类型
func formatPostgreSQLColumnType(columnInfo *models.ColumnInfo) {
	// 如果已经有完整类型信息，直接使用
	if columnInfo.FullType != "" {
		return
	}

	// 按PostgreSQL类型格式构建完整类型
	switch strings.ToLower(columnInfo.Type) {
	case "varchar", "character varying":
		if columnInfo.Length > 0 {
			columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Length)
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	case "numeric", "decimal":
		if columnInfo.Precision > 0 {
			if columnInfo.Scale > 0 {
				columnInfo.FullType = fmt.Sprintf("%s(%d,%d)", columnInfo.Type, columnInfo.Precision, columnInfo.Scale)
			} else {
				columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Precision)
			}
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	default:
		columnInfo.FullType = columnInfo.Type
	}
}

// formatSQLiteColumnType 格式化SQLite列类型
func formatSQLiteColumnType(columnInfo *models.ColumnInfo) {
	// SQLite类型比较简单，通常不需要长度指定
	if columnInfo.FullType == "" {
		columnInfo.FullType = columnInfo.Type
	}
}

// formatSQLServerColumnType 格式化SQL Server列类型
func formatSQLServerColumnType(columnInfo *models.ColumnInfo) {
	// 如果已经有完整类型信息，直接使用
	if columnInfo.FullType != "" {
		return
	}

	// 按SQL Server类型格式构建完整类型
	switch strings.ToLower(columnInfo.Type) {
	case "varchar", "nvarchar", "char", "nchar", "binary", "varbinary":
		if columnInfo.Length > 0 {
			if columnInfo.Length == 2147483647 || columnInfo.Length == -1 {
				// SQL Server中表示MAX
				columnInfo.FullType = fmt.Sprintf("%s(MAX)", columnInfo.Type)
			} else {
				columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Length)
			}
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	case "decimal", "numeric":
		if columnInfo.Precision > 0 {
			if columnInfo.Scale > 0 {
				columnInfo.FullType = fmt.Sprintf("%s(%d,%d)", columnInfo.Type, columnInfo.Precision, columnInfo.Scale)
			} else {
				columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Precision)
			}
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	default:
		columnInfo.FullType = columnInfo.Type
	}
}

// formatDaMengColumnType 格式化达梦列类型
// 注意：此函数已被弃用，由DaMengDriver.buildColumnInfo中的处理逻辑取代
// 保留此函数仅为了向后兼容
func formatDaMengColumnType(columnInfo *models.ColumnInfo) {
	// 如果已经有完整类型信息，直接使用
	if columnInfo.FullType != "" {
		return
	}

	// 按达梦类型格式构建完整类型
	switch strings.ToLower(columnInfo.Type) {
	case "varchar", "varchar2", "char":
		if columnInfo.Length > 0 {
			columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Length)
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	case "number", "decimal", "numeric":
		if columnInfo.Precision > 0 {
			if columnInfo.Scale > 0 {
				columnInfo.FullType = fmt.Sprintf("%s(%d,%d)", columnInfo.Type, columnInfo.Precision, columnInfo.Scale)
			} else {
				columnInfo.FullType = fmt.Sprintf("%s(%d)", columnInfo.Type, columnInfo.Precision)
			}
		} else {
			columnInfo.FullType = columnInfo.Type
		}
	default:
		columnInfo.FullType = columnInfo.Type
	}
}

// ParseDefaultValue 解析不同数据库系统的默认值表示
func ParseDefaultValue(defaultValue string, dbType models.DatabaseType) string {
	if defaultValue == "" {
		return defaultValue
	}

	switch dbType {
	case models.MySQL:
		// MySQL中的一些特殊默认值处理
		if strings.HasPrefix(defaultValue, "CURRENT_TIMESTAMP") {
			return "CURRENT_TIMESTAMP"
		}
		// 移除引号，MySQL中字符串默认值通常带有引号
		if (strings.HasPrefix(defaultValue, "'") && strings.HasSuffix(defaultValue, "'")) ||
			(strings.HasPrefix(defaultValue, "\"") && strings.HasSuffix(defaultValue, "\"")) {
			return defaultValue[1 : len(defaultValue)-1]
		}
	case models.PostgreSQL:
		// PostgreSQL中的一些特殊默认值处理
		if strings.HasPrefix(defaultValue, "nextval(") {
			return "auto-generated"
		}
		// PostgreSQL中的now()函数
		if defaultValue == "now()" || defaultValue == "CURRENT_TIMESTAMP" {
			return "CURRENT_TIMESTAMP"
		}
		// 移除类型转换和引号
		if strings.Contains(defaultValue, "::") {
			parts := strings.Split(defaultValue, "::")
			if len(parts) > 0 {
				value := parts[0]
				// 处理引号
				if (strings.HasPrefix(value, "'") && strings.HasSuffix(value, "'")) ||
					(strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"")) {
					return value[1 : len(value)-1]
				}
				return value
			}
		}
	case models.SQLite:
		// SQLite通常返回原始值，不需要特殊处理
		return defaultValue
	case models.SQLServer:
		// SQL Server中的一些特殊默认值处理
		if strings.Contains(defaultValue, "getdate()") || strings.Contains(defaultValue, "CURRENT_TIMESTAMP") {
			return "CURRENT_TIMESTAMP"
		}
		// 移除括号和引号
		if strings.HasPrefix(defaultValue, "(") && strings.HasSuffix(defaultValue, ")") {
			defaultValue = defaultValue[1 : len(defaultValue)-1]
		}
		if (strings.HasPrefix(defaultValue, "'") && strings.HasSuffix(defaultValue, "'")) ||
			(strings.HasPrefix(defaultValue, "\"") && strings.HasSuffix(defaultValue, "\"")) {
			return defaultValue[1 : len(defaultValue)-1]
		}
	case models.DaMeng:
		// 达梦中的一些特殊默认值处理
		if strings.Contains(defaultValue, "SYSTIMESTAMP") || strings.Contains(defaultValue, "SYSDATE") {
			return "CURRENT_TIMESTAMP"
		}
		// 序列处理
		if strings.Contains(defaultValue, "NEXTVAL") {
			return "auto-generated"
		}
		// 移除引号
		if (strings.HasPrefix(defaultValue, "'") && strings.HasSuffix(defaultValue, "'")) ||
			(strings.HasPrefix(defaultValue, "\"") && strings.HasSuffix(defaultValue, "\"")) {
			return defaultValue[1 : len(defaultValue)-1]
		}
	}

	return defaultValue
}

// IsNumericType 判断是否为数值类型
func IsNumericType(dataType string) bool {
	numericTypes := map[string]bool{
		"tinyint":   true,
		"smallint":  true,
		"mediumint": true,
		"int":       true,
		"integer":   true,
		"bigint":    true,
		"float":     true,
		"double":    true,
		"decimal":   true,
		"numeric":   true,
		"real":      true,
		"bit":       true,
		"number":    true,
	}

	return numericTypes[strings.ToLower(dataType)]
}

// FormatColumns 格式化列信息数组
func FormatColumns(columns []models.ColumnInfo, dbType models.DatabaseType) []models.ColumnInfo {
	for i := range columns {
		FormatColumnType(&columns[i], dbType)

		// 处理默认值
		columns[i].DefaultValue = ParseDefaultValue(columns[i].DefaultValue, dbType)
	}
	return columns
}
